<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/base}">
<head>
    <title>订单管理 - 暖心助农选品平台</title>
</head>
<body>
    <div layout:fragment="content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>订单管理</h2>
            <!-- <a th:href="@{/admin/orders/export}" class="btn btn-secondary">导出数据</a> -->
        </div>

        <div class="card mb-4">
            <div class="card-body">
                <form th:action="@{/admin/orders}" method="get" class="row g-3">
                    <div class="col-md-3">
                        <input type="text" class="form-control" name="keyword" th:value="${param.keyword}" placeholder="搜索订单...">
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="status">
                            <option value="">所有状态</option>
                            <option value="PENDING" th:selected="${param.status == 'PENDING'}">待发货</option>
                            <option value="SHIPPED" th:selected="${param.status == 'SHIPPED'}">已发货</option>
                            <option value="COMPLETED" th:selected="${param.status == 'COMPLETED'}">已完成</option>
                            <option value="CANCELLED" th:selected="${param.status == 'CANCELLED'}">已取消</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100">搜索</button>
                    </div>
                </form>
            </div>
        </div>

        <div th:if="${orders.empty}" class="alert alert-info">
            没有找到符合条件的订单。
        </div>

        <div th:unless="${orders.empty}" class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>订单号</th>
                        <th>下单时间</th>
                        <th>买家</th>
                        <th>农户</th>
                        <th>商品数量</th>
                        <th>总金额</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr th:each="order : ${orders}">
                        <td th:text="${order.id}">订单号</td>
                        <td th:text="${#dates.format(order.createTime, 'yyyy-MM-dd HH:mm:ss')}">下单时间</td>
                        <td th:text="${order.user.realName}">买家</td>
                        <td>
                            <span th:each="item : ${order.items}" th:text="${item.product.farmer.realName}" class="d-block">农户</span>
                        </td>
                        <td th:text="${order.items.size()}">商品数量</td>
                        <td th:text="'￥' + ${order.totalAmount}">总金额</td>
                        <td>
                            <span class="badge" th:classappend="${
                                order.status.name() == 'PENDING' ? 'bg-warning' :
                                order.status.name() == 'SHIPPED' ? 'bg-info' :
                                order.status.name() == 'COMPLETED' ? 'bg-success' :
                                'bg-danger'
                            }" th:text="${
                                order.status.name() == 'PENDING' ? '待发货' :
                                order.status.name() == 'SHIPPED' ? '已发货' :
                                order.status.name() == 'COMPLETED' ? '已完成' :
                                '已取消'
                            }">状态</span>
                        </td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                <a th:href="@{/orders/{id}(id=${order.id})}" class="btn btn-info">详情</a>
                                <button class="btn btn-primary edit-btn"
                                        th:data-order-id="${order.id}"
                                        onclick="editOrder(this.getAttribute('data-order-id'))">编辑</button>
                                <button th:if="${order.status.name() == 'PENDING'}" class="btn btn-danger cancel-btn"
                                        th:data-order-id="${order.id}"
                                        th:data-order-number="${order.id}"
                                        onclick="cancelOrder(this.getAttribute('data-order-id'), this.getAttribute('data-order-number'))">取消</button>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- 编辑订单模态框 -->
        <div class="modal fade" id="editOrderModal" tabindex="-1" aria-labelledby="editOrderModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editOrderModalLabel">编辑订单</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form id="editOrderForm">
                            <input type="hidden" id="editOrderId">
                            <div class="mb-3">
                                <label class="form-label">订单号</label>
                                <input type="text" class="form-control" id="editOrderNumber" readonly>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">买家</label>
                                <input type="text" class="form-control" id="editOrderBuyer" readonly>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">收货人</label>
                                <input type="text" class="form-control" id="editOrderContactName" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">联系电话</label>
                                <input type="tel" class="form-control" id="editOrderContactPhone" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">收货地址</label>
                                <input type="text" class="form-control" id="editOrderDeliveryAddress" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">订单状态</label>
                                <select class="form-select" id="editOrderStatus" required>
                                    <option value="PENDING">待发货</option>
                                    <option value="SHIPPED">已发货</option>
                                    <option value="COMPLETED">已完成</option>
                                    <option value="CANCELLED">已取消</option>
                                </select>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveOrderEdit()">保存</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <th:block layout:fragment="scripts">
        <script th:inline="javascript">
            // 页面加载完成后的初始化
            $(document).ready(function() {
                console.log('Document ready, initializing...');

                // 初始化所有模态框
                var editOrderModal = new bootstrap.Modal(document.getElementById('editOrderModal'));
                console.log('Modal initialized:', editOrderModal);

                // 取消订单
                window.cancelOrder = function(orderId, orderNumber) {
                    if (confirm('确定要取消订单 "' + orderNumber + '" 吗？此操作不可恢复！')) {
                        const baseUrl = /*[[@{/admin/orders}]]*/ '';
                        const url = baseUrl + '/' + orderId + '/cancel';
                        console.log('Cancelling order:', { id: orderId, number: orderNumber, url: url });

                        $.ajax({
                            url: url,
                            type: 'POST',
                            success: function(response) {
                                console.log('Cancel response:', response);
                                if (response === 'success') {
                                    location.reload();
                                } else {
                                    console.error('Cancel failed:', response);
                                    alert('操作失败: ' + response);
                                }
                            },
                            error: function(jqXHR, textStatus, errorThrown) {
                                console.error('Cancel request failed:', {
                                    status: jqXHR.status,
                                    textStatus: textStatus,
                                    errorThrown: errorThrown,
                                    responseText: jqXHR.responseText
                                });
                                alert('操作失败: ' + (jqXHR.responseText || textStatus));
                            }
                        });
                    }
                };

                // 监听模态框关闭事件
                const modalElement = document.getElementById('editOrderModal');
                if (modalElement) {
                    modalElement.addEventListener('hidden.bs.modal', function () {
                        console.log('Modal hidden, resetting form');
                        $('#editOrderForm').trigger('reset');
                    });
                }
            });

            // 编辑订单
            function editOrder(id) {
                console.log('Editing order with ID:', id);
                
                // 构建正确的URL
                const baseUrl = /*[[@{/admin/orders}]]*/ '';
                const url = baseUrl + '/' + id;
                console.log('Fetching order data from:', url);

                $.ajax({
                    url: url,
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        console.log('Received order data:', response);
                        
                        // 检查订单数据是否完整
                        if (!response || !response.id) {
                            console.error('Invalid order data received:', response);
                            alert('获取订单信息失败：数据不完整');
                            return;
                        }

                        try {
                            // 填充表单数据
                            $('#editOrderId').val(response.id);
                            $('#editOrderNumber').val(response.id);
                            $('#editOrderBuyer').val(response.buyerName || '未知');
                            $('#editOrderContactName').val(response.contactName || '');
                            $('#editOrderContactPhone').val(response.contactPhone || '');
                            $('#editOrderDeliveryAddress').val(response.deliveryAddress || '');
                            $('#editOrderStatus').val(response.status || 'PENDING');
                            
                            console.log('Form data filled successfully');

                            // 显示模态框
                            var editOrderModal = bootstrap.Modal.getOrCreateInstance(document.getElementById('editOrderModal'));
                            if (!editOrderModal) {
                                console.error('Failed to get or create modal instance');
                                alert('页面加载错误，请刷新页面后重试');
                                return;
                            }
                            
                            console.log('Showing modal');
                            editOrderModal.show();
                        } catch (error) {
                            console.error('Error filling form data:', error);
                            alert('填充表单数据时发生错误：' + error.message);
                        }
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        console.error('Failed to fetch order data:', {
                            status: jqXHR.status,
                            textStatus: textStatus,
                            errorThrown: errorThrown,
                            responseText: jqXHR.responseText
                        });
                        alert('获取订单信息失败: ' + (jqXHR.responseText || textStatus));
                    }
                });
            }

            // 保存订单编辑
            function saveOrderEdit() {
                const orderData = {
                    id: $('#editOrderId').val(),
                    contactName: $('#editOrderContactName').val(),
                    contactPhone: $('#editOrderContactPhone').val(),
                    deliveryAddress: $('#editOrderDeliveryAddress').val(),
                    status: $('#editOrderStatus').val()
                };

                console.log('Saving order data:', orderData);

                // 构建正确的URL
                const updateUrl = /*[[@{/admin/orders/update}]]*/ '';
                console.log('Saving to URL:', updateUrl);

                $.ajax({
                    url: updateUrl,
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(orderData),
                    success: function(response) {
                        console.log('Save response:', response);
                        if (response === 'success') {
                            var editOrderModal = bootstrap.Modal.getInstance(document.getElementById('editOrderModal'));
                            if (editOrderModal) {
                                editOrderModal.hide();
                            }
                            location.reload();
                        } else {
                            console.error('Save failed:', response);
                            alert('保存失败: ' + response);
                        }
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        console.error('Save request failed:', {
                            status: jqXHR.status,
                            textStatus: textStatus,
                            errorThrown: errorThrown,
                            responseText: jqXHR.responseText
                        });
                        alert('保存失败: ' + (jqXHR.responseText || textStatus));
                    }
                });
            }
        </script>
    </th:block>
</body>
</html> 